package com.neusoft.controller;

import com.neusoft.mapper.PointsMapper;
import com.neusoft.po.CommonResult;
import com.neusoft.po.Points;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

import static org.apache.commons.lang.time.DateUtils.addDays;

@RestController
@RequestMapping("/PointsController")
public class PointsController {

	@Autowired
	private PointsMapper pointsMapper;

	// 获取用户的可用积分
	@GetMapping("/available/{userId}")
	public CommonResult getAvailablePoints(@PathVariable("userId") String userId) {
		Date currentDate = new Date();
		Date expiryDate = addDays(currentDate, 180); // 计算180天后的日期
		List<Points> list = pointsMapper.getAvailablePoints(userId, expiryDate);
		return new CommonResult(200, "success", list);
	}

	// 获取用户的过期积分
	@GetMapping("/expired/{userId}")
	public CommonResult getExpiredPoints(@PathVariable("userId") String userId) {
		Date currentDate = new Date();
		Date expiryDate = addDays(currentDate, 180); // 计算180天后的日期
		List<Points> list = pointsMapper.getExpiredPoints(userId, expiryDate);
		return new CommonResult(200, "success", list);
	}

	// 获取用户的总可用积分
	@GetMapping("/total/{userId}")
	public CommonResult getTotalAvailablePoints(@PathVariable("userId") String userId) {
		Date currentDate = new Date();
		Date expiryDate = addDays(currentDate, 180); // 计算180天后的日期
		Integer totalPoints = pointsMapper.getTotalAvailablePoints(userId, expiryDate);
		return new CommonResult(200, "success", totalPoints);
	}

	// 使用积分
	@PostMapping("/use/{userId}/{pointsToUse}")
	public CommonResult usePoints(@PathVariable("userId") String userId,
								  @PathVariable("pointsToUse") Integer pointsToUse) {
		Date currentDate = new Date();
		pointsMapper.usePoints(userId, -1*pointsToUse, currentDate);
		return new CommonResult(200, "success", "Points used successfully");
	}

	// 增加积分
	@PostMapping("/add/{userId}/{pointsToAdd}")
	public CommonResult addPoints(@PathVariable("userId") String userId,
								  @PathVariable("pointsToAdd") Integer pointsToAdd) {
		Date currentDate = new Date();
		pointsMapper.addPoints(userId, pointsToAdd, currentDate);
		return new CommonResult(200, "success", "Points added successfully");
	}
}